package cn.com.ccxcredit.wallet;

import org.bitcoinj.core.Base58;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.crypto.ChildNumber;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.crypto.HDKeyDerivation;
import org.bitcoinj.crypto.HDUtils;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.wallet.DeterministicKeyChain;
import org.bitcoinj.wallet.DeterministicSeed;
import org.bitcoinj.wallet.UnreadableWalletException;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.Keys;
import org.web3j.crypto.MnemonicUtils;

import java.math.BigInteger;
import java.util.List;

import credit.ccx.com.walletcore.util.MyMnemonicUtils;

import static org.bitcoinj.core.Utils.HEX;

/**
 * Created by gongdongyang on 2018/7/5.
 */

public class Test {
    private static final MainNetParams mainnetParams = new MainNetParams();

    public static void main(String[] args) throws UnreadableWalletException {
        // TODO Auto-generated method stub
        String seedCode = "client dune unfair assume level width bind control mad member old crystal";
        byte[] seed = MnemonicUtils.generateSeed(seedCode, "");
        // BitcoinJ
        DeterministicSeed deterministicSeed = new DeterministicSeed(seedCode, null, "", 1409478661L);
        System.out.println(deterministicSeed.toHexString());
        DeterministicKeyChain chain = DeterministicKeyChain.builder().seed(deterministicSeed).build();

        List<ChildNumber> keyPath = HDUtils.parsePath("M/44H/60H/0H/0/0");
        DeterministicKey key = chain.getKeyByPath(keyPath, true);

        System.out.println(Base58.encode(seed));

        BigInteger privKey = key.getPrivKey();

        // Web3j
        Credentials credentials = Credentials.create(privKey.toString(16));
        String address = credentials.getAddress();
        String privateKey = privKey.toString(16);
        System.out.println(address);
        System.out.println(privateKey);

    }


    public static String getEthAddress(int addressIndex, String ext_key) {
        DeterministicKey parentDK = DeterministicKey.deserializeB58(ext_key, mainnetParams);
        DeterministicKey childDK = HDKeyDerivation.deriveChildKey(parentDK, addressIndex);
        ECKey uncompressedChildKey = childDK.decompress();
        //以太坊需要把前缀去掉（0x04前缀表示未压缩）
        String hexK = uncompressedChildKey.getPublicKeyAsHex().substring(2);
        String addr = Keys.getAddress(hexK);
        return Keys.toChecksumAddress(addr);
    }
}
